package com.colter.project.data.structure.stack;

import java.util.Stack;

public class MinStack<E extends Comparable> extends Stack<E> {

    private Stack<Integer> indexStack;

    public MinStack() {
        indexStack = new Stack<>();
    }

    @Override
    public E push(E item) {
        int minIndex = indexStack.peek();
        E min = elementAt(minIndex);
        if (min.compareTo(item) >= 0) {
            indexStack.push(this.size());
        }
        return super.push(item);
    }

    @Override
    public synchronized E pop() {
        int size = this.size();
        Integer minIndex = indexStack.peek();
        if (minIndex == size - 1) {
            indexStack.pop();
        }
        return super.pop();
    }

    public synchronized E getMin() {
        return elementAt(indexStack.peek());
    }

}
